/*
 * Copyright (c) 2017 Solidwang. All Rights Reserved
 */
package com.solid4j.auth.dao.impl;


import com.solid4j.auth.dao.BaseDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * @author: solidwang
 * @date: 17/4/17
 */
@Component(value = "baseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Resource
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Integer save(T t) {
        Session session = getCurrentSession();
        Serializable s = session.save(t);
        session.flush();
        return s instanceof Integer ? ((Integer) s) : null;
    }

    @Override
    public void update(T model) {
        Session session = getCurrentSession();
        session.update(model);
        session.flush();
    }

    @Override
    public void delete(T model) {
        Session session = getCurrentSession();
        session.delete(model);
        session.flush();
    }

    @Override
    public T get(Class<T> clazz, Serializable id) {
        return (T) getCurrentSession().get(clazz, id);
    }

    @Override
    public List<T> getList(String hql) {
        Session session = getCurrentSession();
        try {
            List<T> list = session.createQuery(hql).list();
            if (list == null || list.size() <= 0) {
                return null;
            }
            return session.createQuery(hql).list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
